
#include "clib_random_clock.h"
#include "../../time/clib_time.h"
#include <pthread.h>
#include <sys/time.h>

#define CLIB_RANDOM_CLOCK_SEED_INIT     (2166136261ul)

static size_t g_value = CLIB_RANDOM_CLOCK_SEED_INIT;

static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

static void clib_random_clock_set_seed(size_t seed) {
    pthread_mutex_lock(&lock);
    g_value = seed;
    pthread_mutex_unlock(&lock);
}

static clib_uint64_t clib_random_clock_get_value() {
    pthread_mutex_lock(&lock);
    g_value = (g_value * 10807 + 1) & 0xffffffff;
    pthread_mutex_unlock(&lock);
    return g_value;
}

static void clib_random_clock_reset() {
    size_t seed = CLIB_RANDOM_CLOCK_SEED_INIT;
    clib_uint64_t clock = clib_time_get_nanosecond_timestamp();
    // 初始化种子
    seed = (size_t) ((clock >> 32) ^ clock);

    // xor 地址值
    seed ^= CLIB_CAST_TO_SIZE(&seed);
    clib_random_clock_set_seed(seed);
}

clib_int64_t clib_random_clock() {
    clib_random_clock_reset();
    return CLIB_CAST_TO_INT64(clib_random_clock_get_value());
}

clib_int64_t clib_random_clock_range(clib_int64_t begin, clib_int64_t end) {
    return (begin + CLIB_CAST_TO_INT64((clib_random_clock_get_value() % (end - begin))));
}